<template>
  <div>
    <!-- 面包屑导航区域 -->
    <div class="board">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>场次管理</el-breadcrumb-item>
        <el-breadcrumb-item>场次信息管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select v-model="selectedMovieId" placeholder="请选择电影名称" clearable>
            <el-option
              v-for="item in movieList"
              :key="item.movieId"
              :label="item.movieNameCn"
              :value="item.movieId"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button icon="el-icon-search" @click="getMovieList">搜索</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="showAddDialog">添加场次</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="danger" @click="multipleDelete">批量删除</el-button>
        </el-col>
      </el-row>

      <!-- 使用表格组件展示电影列表 -->
      <el-table
        :data="movieList"
        style="width: 100%"
        border
        stripe
        @row-click="handleRowClick"
        highlight-current-row
      >
        <el-table-column prop="movieNameCn" label="电影名称" width="300"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="getMovieSessionInfo(scope.row.movieId)"
            >
              查看场次
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 电影场次信息对话框 -->
      <el-dialog
        title="电影场次信息"
        :visible.sync="sessionIsShow"
        width="80%"
        :modal-append-to-body="false"
        @close="handleDrawerClose"
      >
        <el-table :data="sessionList" style="width: 100%;" border stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="sysCinema.cinemaName" label="影院名称" width="140px"></el-table-column>
          <el-table-column prop="sysHall.hallName" label="影厅名称"></el-table-column>
          <el-table-column prop="languageVersion" label="语言"></el-table-column>
          <el-table-column prop="sysMovie.movieNameCn" label="电影名称"></el-table-column>
          <el-table-column prop="sysMovieRuntime.movieRuntimeName" label="播放时段"></el-table-column>
          <el-table-column prop="sessionDate" label="场次时间"></el-table-column>
          <el-table-column prop="sessionPrice" label="场次价格"></el-table-column>
          <el-table-column prop="sessionTips" label="提示信息"></el-table-column>
          <el-table-column prop="sessionState" label="场次状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.sessionState" @change="sessionStateChanged(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template slot-scope="scope">
              <el-tooltip effect="dark" content="修改场次信息" placement="top" :enterable="false" :open-delay="500">
                <el-button
                  v-if="isCinemaOwner(scope.row.cinemaId)"
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scope.row.sessionId)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="删除影厅" placement="top" :enterable="false" :open-delay="500">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteSessionById(scope.row.sessionId)"
                ></el-button>
              </el-tooltip>
              <el-tooltip effect="dark" content="查看座位" placement="top" :enterable="false" :open-delay="500">
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                  @click="checkSeat(scope.row.sessionId)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页区域 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 7, 9]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          style="margin-top: 20px;"
        ></el-pagination>
      </el-dialog>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 7, 9]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加场次对话框 -->
    <el-dialog title="添加场次" :visible.sync="addDialogVisible" width="60%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="150px">
        <el-form-item label="影院名称" prop="cinemaId">
          <el-input v-model="curCinemaName" disabled></el-input>
        </el-form-item>
        <el-form-item label="影厅名称" prop="hallId">
          <el-select v-model="addForm.hallId" placeholder="请选择影厅名称" clearable>
            <el-option
              v-for="item in hallList"
              :key="item.hallId"
              :label="item.hallName"
              :value="item.hallId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语言版本" prop="languageVersion">
          <el-input v-model="addForm.languageVersion"></el-input>
        </el-form-item>
        <el-form-item label="电影名称" prop="movieId">
          <el-select v-model="addForm.movieId" placeholder="请选择电影名称" clearable>
            <el-option
              v-for="item in movieList"
              :key="item.movieId"
              :label="item.movieNameCn"
              :value="item.movieId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="播放时段" prop="movieRuntimeId">
          <el-select v-model="addForm.movieRuntimeId" placeholder="请选择播放时段" clearable>
            <el-option
              v-for="item in movieRuntimeList"
              :key="item.movieRuntimeId"
              :label="item.movieRuntimeName"
              :value="item.movieRuntimeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场次日期" prop="sessionDate">
          <el-date-picker
            v-model="addForm.sessionDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <!-- 新增：开始时间选择器 -->
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="addForm.startTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="场次价格" prop="sessionPrice">
          <el-input v-model="addForm.sessionPrice"></el-input>
        </el-form-item>
        <el-form-item label="提示信息" prop="sessionTips">
          <el-input v-model="addForm.sessionTips"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addSession">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改场次对话框 -->
    <el-dialog title="修改场次" :visible.sync="editDialogVisible" width="60%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="150px">
        <el-form-item label="影院名称" prop="cinemaId">
          <el-input v-model="curCinemaName" disabled></el-input>
        </el-form-item>
        <el-form-item label="影厅名称" prop="hallId">
          <el-select v-model="editForm.hallId" placeholder="请选择影厅名称" clearable>
            <el-option
              v-for="item in hallList"
              :key="item.hallId"
              :label="item.hallName"
              :value="item.hallId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="语言版本" prop="languageVersion">
          <el-input v-model="editForm.languageVersion"></el-input>
        </el-form-item>
        <el-form-item label="电影名称" prop="movieId">
          <el-select v-model="editForm.movieId" placeholder="请选择电影名称" clearable>
            <el-option
              v-for="item in movieList"
              :key="item.movieId"
              :label="item.movieNameCn"
              :value="item.movieId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="播放时段" prop="movieRuntimeId">
          <el-select v-model="editForm.movieRuntimeId" placeholder="请选择播放时段" clearable>
            <el-option
              v-for="item in movieRuntimeList"
              :key="item.movieRuntimeId"
              :label="item.movieRuntimeName"
              :value="item.movieRuntimeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="场次日期" prop="sessionDate">
          <el-date-picker
            v-model="editForm.sessionDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <!-- 新增：开始时间选择器（修改场次时回显） -->
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker
            v-model="editForm.startTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
          ></el-time-picker>
        </el-form-item>
        <el-form-item label="场次价格" prop="sessionPrice">
          <el-input v-model="editForm.sessionPrice"></el-input>
        </el-form-item>
        <el-form-item label="提示信息" prop="sessionTips">
          <el-input v-model="editForm.sessionTips"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSessionInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 安排座位对话框 -->
    <el-dialog title="查看座位" :visible.sync="checkDialogVisible" :width="checkDialogWidth">
      <div style="display:flex; align-content: center">
        <span style="margin-right: 10px">启用</span>
        <span class="seat" :class="isSelected[0]"></span>
        <span style="margin: 0 10px">禁用</span>
        <span class="seat" :class="isSelected[1]"></span>
        <span style="margin: 0 10px">售出</span>
        <span class="seat" :class="isSelected[2]"></span>
      </div>
      <br />
      <div class="row" v-for="(value, key) in seats">
        <span style="margin-right: 100px">{{ key }}</span>
        <div style="display: flex; justify-content: flex-end">
          <span
            class="seat"
            :class="isSelected[seats[key][index]]"
            v-for="(item, index) in value"
          ></span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import global from "@/assets/css/global.css";
export default {
  name: "HallInfo",
  data() {
    return {
      queryInfo: {
        sessionId: "",
        cinemaId: "",
        movieId: "",
        movieRuntimeId: "",
        sessionDate: "",
        pageNum: 1,
        pageSize: 7,
      },
      sessionList: [],
      total: 0,
      // 控制对话框的显示与隐藏
      addDialogVisible: false,
      // 添加影厅的表单数据
      addForm: {
        cinemaId: "",
        hallId: "",
        languageVersion: "",
        movieId: "",
        movieRuntimeId: "",
        sessionDate: "",
        sessionState: true,
        sessionPrice: "",
        sessionTips: "",
        sessionSeats: "",
        seatNums: 0,
        startTime: "", // 新增：绑定开始时间
      },
      // 验证表单规则对象
      addFormRules: {
        hallId: [
          { required: true, message: "请选择影厅名称", trigger: "change" },
        ],
        languageVersion: [
          { required: true, message: "请输入电影语言", trigger: "blur" },
        ],
        movieId: [
          { required: true, message: "请选择电影名称", trigger: "change" },
        ],
        movieRuntimeId: [
          { required: true, message: "请选择播放时段", trigger: "change" },
        ],
        sessionDate: [
          { required: true, message: "请选择场次日期", trigger: "blur" },
        ],
        sessionPrice: [
          { required: true, message: "请输入场次价格", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
        ], // 新增：开始时间校验
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        hallId: [
          { required: true, message: "请选择影厅名称", trigger: "change" },
        ],
        languageVersion: [
          { required: true, message: "请输入电影语言", trigger: "blur" },
        ],
        movieId: [
          { required: true, message: "请选择电影名称", trigger: "change" },
        ],
        movieRuntimeId: [
          { required: true, message: "请选择播放时段", trigger: "change" },
        ],
        sessionDate: [
          { required: true, message: "请选择场次日期", trigger: "blur" },
        ],
        sessionPrice: [
          { required: true, message: "请输入场次价格", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "请选择开始时间", trigger: "blur" },
        ], // 新增：修改时校验
      },
      selectedCinemaId: "",
      selectedMovieId: "",
      selectedMovieRuntimeId: "",
      selectedDate: "",
      cinemaList: [],
      hallList: [],
      movieList: [],
      movieRuntimeList: [],
      states: [
        {
          id: 0,
          name: "已下架",
        },
        {
          id: 1,
          name: "上映中",
        },
      ],
      multipleSelection: [],
      checkDialogVisible: false,
      seats: {},
      col: "",
      isSelected: {
        0: "seat-default",
        1: "seat-choose",
        3: "seat-sold",
      },
      editSeat: {},
      checkDialogWidth: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      rowNums: "",
      colNums: "",
      rowStart: "",
      curCinemaName: "",
      loginUser: JSON.parse(window.sessionStorage.getItem("loginUser")),
      // 控制电影场次信息表单的显隐
      sessionIsShow: false,
      // 新增：数据加载状态
      loading: {
        hallList: false,
        movieList: false,
        cinemaList: false,
        movieRuntimeList: false,
        sessionList: false,
      },
      // 新增：数据加载错误状态
      error: {
        hallList: false,
        movieList: false,
        cinemaList: false,
        movieRuntimeList: false,
        sessionList: false,
      },
    };
  },
  created() {
    // 使用 async/await 处理数据加载顺序
    this.initData();
  },
  methods: {
    // 初始化数据
    async initData() {
      try {
        // 先获取影院信息，确保影院名称已加载
        this.curCinemaName = this.loginUser.cinemaName;
        
        // 并行加载数据
        await Promise.all([
          this.getHallList(),
          this.getMovieList(),
          this.getCinemaList(),
          this.getMovieRuntimeList()
        ]);
        
        // 最后加载场次列表
        await this.getSessionList();
      } catch (error) {
        console.error('初始化数据失败:', error);
        this.$message.error('数据加载失败，请刷新页面重试');
      }
    },
    
    // 新增表格行点击方法
    handleRowClick(row) {
      this.getMovieSessionInfo(row.movieId);
    },
    
    // 获取场次列表
    async getSessionList() {
      this.loading.sessionList = true;
      this.error.sessionList = false;
      
      try {
        this.queryInfo.cinemaId = this.selectedCinemaId;
        console.log("请求参数", this.queryInfo);
        
        // 非系统管理员只能查看自己影院的场次信息
        if (window.sessionStorage.getItem("btnPermission") === "normal") {
          this.queryInfo.cinemaId = JSON.parse(
            window.sessionStorage.getItem("loginUser")
          ).cinemaId;
        }
        
        this.queryInfo.movieId = this.selectedMovieId;
        this.queryInfo.movieRuntimeId = this.selectedMovieRuntimeId;
        this.queryInfo.sessionDate = this.selectedDate;
        console.log(String(this.selectedDate));
        
        const resp = await axios.get("sysSession", { params: this.queryInfo });
        console.log(resp);
        
        this.sessionList = resp.data.data;
        this.total = resp.data.total;
        this.queryInfo.pageSize = resp.data.pageSize;
        this.queryInfo.pageNum = resp.data.pageNum;
      } catch (error) {
        console.error('获取场次列表失败:', error);
        this.error.sessionList = true;
        this.$message.error('获取场次列表失败，请检查网络连接');
      } finally {
        this.loading.sessionList = false;
      }
    },
    
    // 获取影厅列表
    async getHallList() {
      this.loading.hallList = true;
      this.error.hallList = false;
      
      try {
        const resp = await axios.get("sysHall?cinemaId=" + this.loginUser.cinemaId);
        this.hallList = resp.data.data;
      } catch (error) {
        console.error('获取影厅列表失败:', error);
        this.error.hallList = true;
        this.$message.error('获取影厅列表失败，请检查网络连接');
      } finally {
        this.loading.hallList = false;
      }
    },
    
    // 获取影院列表
    async getCinemaList() {
      this.loading.cinemaList = true;
      this.error.cinemaList = false;
      
      try {
        const resp = await axios.get("sysCinema");
        this.cinemaList = resp.data.data;
      } catch (error) {
        console.error('获取影院列表失败:', error);
        this.error.cinemaList = true;
        this.$message.error('获取影院列表失败，请检查网络连接');
      } finally {
        this.loading.cinemaList = false;
      }
    },
    
    // 获取电影列表
    async getMovieList() {
      this.loading.movieList = true;
      this.error.movieList = false;
      
      try {
        const resp = await axios.get("sysMovie");
        this.movieList = resp.data.data;
        
        if (this.selectedMovieId) {
          this.movieList = this.movieList.filter(
            (item) => item.movieId === this.selectedMovieId
          );
        }
        
        console.log("电影信息movieList：" + JSON.stringify(this.movieList));
      } catch (error) {
        console.error('获取电影列表失败:', error);
        this.error.movieList = true;
        this.$message.error('获取电影列表失败，请检查网络连接');
      } finally {
        this.loading.movieList = false;
      }
    },
    
    // 获取电影场次信息
    getMovieSessionInfo(movieId) {
      this.sessionIsShow = true;
      this.selectedMovieId = movieId;
      this.getSessionList();
    },
    
    // 获取电影时段列表
    async getMovieRuntimeList() {
      this.loading.movieRuntimeList = true;
      this.error.movieRuntimeList = false;
      
      try {
        const resp = await axios.get("sysMovieRuntime");
        console.log(resp);
        this.movieRuntimeList = resp.data.data;
      } catch (error) {
        console.error('获取电影时段列表失败:', error);
        this.error.movieRuntimeList = true;
        this.$message.error('获取电影时段列表失败，请检查网络连接');
      } finally {
        this.loading.movieRuntimeList = false;
      }
    },
    
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getSessionList();
      console.log(newSize);
    },
    
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getSessionList();
      console.log(newPage);
    },
    
    showAddDialog() {
      // 重置开始时间
      this.addForm.startTime = "";
      this.addDialogVisible = true;
    },
    
    // 监听添加对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    
    // 监听添加按钮
    async addSession() {
      const _this = this;
      
      this.$refs.addFormRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        // 验证通过，将登录用户的影院id赋值给表单
        this.addForm.cinemaId = this.loginUser.cinemaId;

        try {
          // 查询影厅信息，查出对应排数和排座位数，填充sessionSeats字段
          const hallResp = await axios.get("sysHall/" + this.addForm.cinemaId + "/" + this.addForm.hallId);
          
          _this.rowNums = hallResp.data.data.rowNums;
          _this.colNums = hallResp.data.data.seatNumsRow;
          _this.rowStart = hallResp.data.data.rowStart;
          const seats = hallResp.data.data.seatState;

          // 新建场次时，将影厅的座位信息赋值给场次
          this.$set(this.addForm, "sessionSeats", seats);
          console.log(_this.addForm.sessionSeats);

          // 发送请求
          axios.defaults.headers.post["Content-Type"] = "application/json";
          const resp = await axios.post("sysSession", this.addForm);
          console.log(resp);
          
          if (resp.data.code === 200) {
            this.$message.success("添加场次信息成功！");
            this.addDialogVisible = false;
            this.getSessionList();
          } else {
            this.$message.error("添加场次信息失败！");
            this.$message.error(resp.data.msg);
          }
        } catch (error) {
          console.error('添加场次失败:', error);
          this.$message.error('添加场次信息失败，请检查网络连接');
        }
      });
    },
    
    // 显示修改对话框，回显数据
    async showEditDialog(id) {
      try {
        const { data: res } = await axios.get("sysSession/" + id);
        this.editForm = res.data;
        
        // 从完整的 beginTime 中提取时间部分（格式为 "yyyy-MM-dd HH:mm:ss"）
        if (this.editForm.beginTime) {
          const timePart = this.editForm.beginTime.split(" ")[1];
          this.editForm.startTime = timePart;
        }
        
        this.editDialogVisible = true;
      } catch (error) {
        console.error('获取场次详情失败:', error);
        this.$message.error('获取场次详情失败，请检查网络连接');
      }
    },
    
    // 监听修改对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    
    // 修改场次信息并提交
    async editSessionInfo() {
      this.editForm.cinemaId = this.loginUser.cinemaId;
      let row = this.editForm.rowNums;
      let col = this.editForm.seatNumsRow;
      this.$set(this.editForm, "seatNums", row * col);
      
      let seat = {};
      for (let i = 0; i < row; i++) {
        let arr = [];
        for (let j = 0; j < col; j++) {
          arr.push(0);
        }
        seat[
          isNaN(parseInt(this.editForm.rowStart))
            ? String.fromCharCode(i + this.editForm.rowStart.charCodeAt(0))
            : i + parseInt(this.editForm.rowStart)
        ] = arr;
      }
      
      this.$set(this.editForm, "seatState", JSON.stringify(seat));

      this.$refs.editFormRef.validate(async (valid) => {
        const _this = this;
        if (!valid) return;
        
        try {
          let success = true;
          axios.defaults.headers.put["Content-Type"] = "application/json";
          const resp = await axios.put("/sysSession", this.editForm);
          
          if (resp.data.code !== 200) {
            this.$message.error("修改场次信息失败！");
            this.$message.error(resp.data.message);
            success = false;
          }
          
          if (!success) return;
          this.editDialogVisible = false;
          this.getSessionList();
          this.$message.success("修改场次信息成功！");
        } catch (error) {
          console.error('修改场次失败:', error);
          this.$message.error('修改场次信息失败，请检查网络连接');
        }
      });
    },
    
    // 监听多选框变化
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 处理抽屉关闭事件
    handleDrawerClose() {
      // 重置查询条件
      this.queryInfo.movieId = "";
      this.selectedMovieId = "";
    },
    
    // 检查是否是当前影院的所有者
    isCinemaOwner(cinemaId) {
      return cinemaId === this.loginUser.cinemaId;
    },
    
    // 批量删除场次
    async multipleDelete() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请至少选择一条记录！");
        return;
      }
      
      this.$confirm("确定要删除选中的场次信息吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          const ids = this.multipleSelection.map(item => item.sessionId);
          const resp = await axios.delete("sysSession/" + ids.join(','));
          
          if (resp.data.code === 200) {
            this.$message.success("删除场次信息成功！");
            this.getSessionList();
          } else {
            this.$message.error("删除场次信息失败！");
            this.$message.error(resp.data.message);
          }
        } catch (error) {
          console.error('批量删除失败:', error);
          this.$message.error('删除场次信息失败，请检查网络连接');
        }
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    // 删除单个场次
    async deleteSessionById(id) {
      this.$confirm("确定要删除该场次信息吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(async () => {
        try {
          const resp = await axios.delete("sysSession/" + id);
          
          if (resp.data.code === 200) {
            this.$message.success("删除场次信息成功！");
            this.getSessionList();
          } else {
            this.$message.error("删除场次信息失败！");
            this.$message.error(resp.data.message);
          }
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error('删除场次信息失败，请检查网络连接');
        }
      }).catch(() => {
        // 用户取消操作
      });
    },
    
    // 检查座位
    async checkSeat(sessionId) {
      try {
        const resp = await axios.get("sysSession/seats/" + sessionId);
        this.seats = JSON.parse(resp.data.data.sessionSeats);
        this.checkDialogVisible = true;
        
        // 根据座位数量动态调整对话框宽度
        const maxCols = Math.max(...Object.values(this.seats).map(row => row.length));
        this.checkDialogWidth = Math.min(90, 30 + maxCols * 2) + '%';
      } catch (error) {
        console.error('获取座位信息失败:', error);
        this.$message.error('获取座位信息失败，请检查网络连接');
      }
    },
    
    // 场次状态变更
    async sessionStateChanged(row) {
      try {
        const resp = await axios.put("sysSession/state", {
          sessionId: row.sessionId,
          sessionState: row.sessionState
        });
        
        if (resp.data.code === 200) {
          this.$message.success(row.sessionState ? "场次已上架！" : "场次已下架！");
        } else {
          this.$message.error("更新场次状态失败！");
          this.$message.error(resp.data.message);
          // 恢复原始状态
          row.sessionState = !row.sessionState;
        }
      } catch (error) {
        console.error('更新场次状态失败:', error);
        this.$message.error('更新场次状态失败，请检查网络连接');
        // 恢复原始状态
        row.sessionState = !row.sessionState;
      }
    },
  }
}
</script>

<style scoped>
/* 表格样式调整 */
.el-table {
  font-size: 14px; /* 增加字体大小 */
}

.el-table th, .el-table td {
  padding: 12px 16px; /* 增加单元格内边距 */
  height: 48px; /* 增加行高 */
}

/* 表头样式 */
.el-table thead th {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 表格行悬停效果 */
.el-table tbody tr:hover {
  background-color: #f2f8ff;
}

/* 座位样式 */
.seat {
  width: 20px;
  height: 20px;
  margin: 2px;
  border-radius: 2px;
  display: inline-block;
}

.seat-default {
  background-color: #409eff;
}

.seat-choose {
  background-color: #67c23a;
}

.seat-sold {
  background-color: #f56c6c;
}

.row {
  display: flex;
  align-items: center;
  margin: 5px 0;
}
</style>